#include <Common/Common.h>
#include <iostream>
#include <errno.h>
using namespace std;

class CListenerEvent : public IListenerEvent
{
    virtual Bool OnAccept(Int32 nListenFD, Int32 nClientFD, const CSocketAddr &addr)
    {
        cout << "OnAccept. ListenFD=" << nListenFD << ",ClientFD=" << nClientFD
             << ",Address=" << addr.GetAddrString() << endl;

        return True;
    }
};

class CClient : public ITimerEvent
{
public:
    CClient(CEventEngine *pEngine)
        : m_timer(pEngine, this)
    {
        m_timer.SetTimer(5000);
    }

private:
    virtual void OnTimer(CTimer *pTimer)
    {
        CTCPSocket sock;
        sock.Create(AF_IPv6);
        if (sock.Connect("[::1]:30000"))
        {
            cout << "Connect to server OK" << endl;
        }
        else
        {
            cerr << "failed to connect to server. errno=" << errno << endl;
        }
    }

private:
    CTimer  m_timer;
};

Int32 main()
{
    OS::Initialize();
    CEventEngine engine;
    engine.Initialize();

    CListenerEvent listenCallback;
    CInetListener listener4(&engine, &listenCallback);
    CInetListener listener6(&engine, &listenCallback);
    if (!listener4.Start("0.0.0.0:30000"))
    {
        cerr << "failed to listen IPv4. errno=" << errno << endl;
    }

    if (!listener6.Start("[::]:30000"))
    {
        cerr << "failed to listen IPv6. errno=" << errno << endl;
    }

    new CClient(&engine);

    while (1)
    {
        engine.Loop(500);
    }

    return 0;
}
